<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { ShoppingCart, CaretBottom, Shop } from '@element-plus/icons-vue';
// 假设我们有一个简单的 auth store 或 event bus 来更新登录状态
// For simplicity, we'll continue using localStorage and watch for changes

const router = useRouter();
const route = useRoute();
const isLoggedIn = ref(!!localStorage.getItem('user_token'));
const activeIndex = ref('/'); // For el-menu active state
const cartItemCount = ref(0);
const username = ref('用户');
const userAvatar = ref('https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png');

// Update isLoggedIn when localStorage changes (e.g., from other tabs or direct manipulation)
const handleStorageChange = (event) => {
  if (event.key === 'user_token') {
    isLoggedIn.value = !!event.newValue;
  }
};

onMounted(() => {
  window.addEventListener('storage', handleStorageChange);
  // Set activeIndex based on current route
  activeIndex.value = route.path;
});

onUnmounted(() => {
  window.removeEventListener('storage', handleStorageChange);
  // 清理其他可能的副作用
  isLoggedIn.value = false;
  activeIndex.value = '/';
});

// Watch route changes to update activeIndex for the menu
watch(() => route.path, (newPath) => {
  activeIndex.value = newPath;
  // Also re-check login status on route change, useful if a route guard logs out user
  isLoggedIn.value = !!localStorage.getItem('user_token');
});

const handleCommand = async (command) => {
  try {
    switch (command) {
      case 'profile':
        await router.push('/profile');
        break;
      case 'orders':
        await router.push('/orders');
        break;
      case 'logout':
        await logout();
        break;
    }
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败，请稍后重试');
  }
};

const logout = async () => {
  try {
    localStorage.removeItem('user_token');
    isLoggedIn.value = false;
    ElMessage.success('您已成功登出');
    await router.push({ name: 'Login' });
  } catch (error) {
    console.error('登出失败:', error);
    ElMessage.error('登出失败，请稍后重试');
  }
};

const handleMenuSelect = async (key) => {
  try {
    if (key === '/logout') {
      await logout();
    } else {
      await router.push(key);
    }
  } catch (error) {
    console.error('路由导航错误:', error);
    ElMessage.error('页面跳转失败，请稍后重试');
  }
};

// 添加路由错误处理
router.onError((error) => {
  console.error('路由错误:', error);
  ElMessage.error('页面加载失败，请稍后重试');
  // 如果发生错误，重定向到首页
  router.push('/');
});

</script>

<template>
  <el-container class="app-container">
    <el-header class="app-header">
      <div class="header-content">
        <div class="header-left">
          <el-menu
            :default-active="activeIndex"
            class="el-menu-demo"
            mode="horizontal"
            :ellipsis="false"
            @select="handleMenuSelect"
          >
            <el-menu-item index="/" class="logo-item">
              <el-icon class="logo-icon"><Shop /></el-icon>
              <span class="logo-text">简易商城</span>
            </el-menu-item>
            <el-menu-item index="/">首页</el-menu-item>
            <el-menu-item index="/products">全部商品</el-menu-item>
            <el-menu-item index="/cart" v-if="isLoggedIn">
              <el-badge :value="cartItemCount" :hidden="!cartItemCount" class="cart-badge">
                <el-icon><ShoppingCart /></el-icon>
                购物车
              </el-badge>
            </el-menu-item>
          </el-menu>
        </div>

        <div class="header-right">
          <template v-if="isLoggedIn">
            <el-dropdown trigger="click" @command="handleCommand">
              <span class="user-dropdown">
                <el-avatar :size="32" :src="userAvatar" />
                <span class="username">{{ username }}</span>
                <el-icon><CaretBottom /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                  <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
          <template v-else>
            <el-button type="text" @click="router.push('/login')">登录</el-button>
            <el-button type="primary" @click="router.push('/register')">注册</el-button>
          </template>
        </div>
      </div>
    </el-header>

    <el-main class="app-main">
      <router-view v-slot="{ Component }">
        <transition name="fade" mode="out-in">
          <keep-alive :include="['Home', 'Products', 'Cart']">
            <component :is="Component" :key="$route.fullPath" />
          </keep-alive>
        </transition>
      </router-view>
    </el-main>

    <el-footer class="app-footer">
      <div class="footer-bottom">
        <p>&copy; {{ new Date().getFullYear() }} 简易在线购物商城. 保留所有权利.</p>
        <p>
          <a href="/terms">服务条款</a> | <a href="/privacy">隐私政策</a>
        </p>
      </div>
    </el-footer>
  </el-container>
</template>

<style>
:root {
  --primary-color: #409EFF;
  --header-height: 64px;
  --footer-bg-color: #2c3e50;
  --text-color: #303133;
  --border-color: #e6e6e6;
  --max-width: 1440px;
  --content-padding: 24px;
  --content-width: 1200px;
}

body {
  margin: 0;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB',
    'Microsoft YaHei', '\5FAE\8F6F\96C5\9ED1', Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: var(--text-color);
  background-color: #f5f7fa;
  min-width: 1200px;
}

.app-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.app-header {
  height: var(--header-height);
  padding: 0;
  background-color: #ffffff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  position: fixed;
  width: 100%;
  top: 0;
  z-index: 1000;
}

.header-content {
  width: var(--content-width);
  margin: 0 auto;
  height: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 var(--content-padding);
}

.header-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 24px;
}

.logo-item {
  display: flex;
  align-items: center;
  padding: 0 24px;
  height: 100%;
  transition: background-color 0.3s;
}

.logo-item:hover {
  background-color: #f5f7fa;
}

.logo-icon {
  font-size: 28px;
  color: var(--primary-color);
  margin-right: 12px;
}

.logo-text {
  font-size: 22px;
  font-weight: bold;
  color: var(--primary-color);
  letter-spacing: 1px;
}

.el-menu-demo {
  border-bottom: none;
  height: 100%;
  display: flex;
  align-items: center;
}

.el-menu-item {
  font-size: 15px;
  height: var(--header-height);
  line-height: var(--header-height);
  padding: 0 20px;
  transition: all 0.3s;
}

.el-menu-item:hover {
  background-color: #f5f7fa;
}

.el-menu-item.is-active {
  font-weight: bold;
  color: var(--primary-color) !important;
  border-bottom: 2px solid var(--primary-color);
}

.cart-badge {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 15px;
}

.cart-badge .el-icon {
  font-size: 18px;
}

.user-dropdown {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 6px 12px;
  border-radius: 6px;
  transition: all 0.3s;
}

.user-dropdown:hover {
  background-color: #f5f7fa;
}

.username {
  font-size: 14px;
  color: var(--text-color);
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.app-main {
  flex-grow: 1;
  padding: calc(var(--header-height) + 24px) 0 24px;
  width: 100%;
  box-sizing: border-box;
  background-color: #ffffff;
  min-height: calc(100vh - var(--header-height));
}

/* 添加内容容器样式 */
.content-container {
  width: var(--content-width);
  margin: 0 auto;
  padding: 0 var(--content-padding);
  box-sizing: border-box;
}

/* 全宽容器样式 */
.full-width-container {
  width: 100%;
  padding: 0;
  margin: 0;
}

.app-footer {
  background-color: var(--footer-bg-color);
  color: #ffffff;
  padding: 30px 0;
  width: 100%;
}

.footer-bottom {
  width: var(--content-width);
  margin: 0 auto;
  text-align: center;
  color: #a8b2bc;
  font-size: 14px;
  line-height: 1.8;
  padding: 0 var(--content-padding);
  box-sizing: border-box;
}

.footer-bottom a {
  color: #a8b2bc;
  text-decoration: none;
  transition: color 0.3s;
  margin: 0 8px;
}

.footer-bottom a:hover {
  color: #ffffff;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 响应式设计 */
@media (max-width: 1440px) {
  :root {
    --content-width: 1200px;
    --content-padding: 20px;
  }
}

@media (max-width: 1200px) {
  :root {
    --content-width: 960px;
    --content-padding: 16px;
  }
  
  .footer-content {
    grid-template-columns: repeat(2, 1fr);
    gap: 40px;
  }
}

@media (max-width: 960px) {
  :root {
    --content-width: 720px;
    --content-padding: 12px;
  }
  
  .header-right {
    gap: 16px;
  }
  
  .logo-text {
    font-size: 18px;
  }
  
  .el-menu-item {
    padding: 0 12px;
  }
}
</style>
